<script setup>
import Topbar from "@/components/Topbar/index.vue";
import FormTitle from "@/components/Form/FormTitle.vue";
import Form from "@/components/Form/index.vue";
import { rulePassword, ruleTelephone } from "@/utils/rules.js";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import {
  queryDepartmentListPage,
  queryRoleList,
  operationSysUser,
  querySysUserDetail,
  queryDataPermissionList,
  dataGroupAuthStore,
} from "@/api/System";
import md5 from 'md5'
import { useRoute } from "vue-router";
const route = useRoute();
const baseformRef = ref();
const baseformList = ref([
  {
    type: "input",
    key: "employeeName",
    label: "员工姓名",
    width: "260px",
    maxlength: "20",
    clearable: true,
  },
  {
    type: "input",
    key: "userAccount",
    label: "登录账号",
    clearable: true,
    width: "260px",
    maxlength: "11",
    placeholder: "请输入11位有效手机号",
  },
  {
    type: "password",
    key: "userPassword",
    label: "登录密码",
    width: "260px",
    clearable: true,
  },
  {
    type: "select",
    key: "departmentIdList",
    width: "260px",
    list: [],
    label: "所属部门",
    multiple: true,
    clearable: true,
    remote: true,
    loading: false,
  },
  {
    type: "input",
    key: "userRemark",
    label: "备注",
    width: "260px",
    clearable: true,
    maxlength: "100",
  },
]);
const rulePasswordFun = (rule, value, callback) => {
  if (value == "********") {
    return callback();
  } else {
    if (!rulePassword(value)) {
      return callback(new Error("请输入8-20位字母+数字+特殊字符"));
    }
    return callback();
  }
};
const ruleIphoneFun = (rule, value, callback) => {
  if (!ruleTelephone(value)) {
    return callback(new Error("请输入正确的手机号"));
  }
  return callback();
};

const baseformRules = {
  employeeName: [
    { required: true, message: "请输入员工姓名", trigger: "change" },
  ],
  userAccount: [
    { required: true, message: "请输入登录账号", trigger: "change" },
    { validator: ruleIphoneFun },
  ],
  userPassword: [
    { required: true, message: "请输入登录密码", trigger: "change" },
    { validator: rulePasswordFun },
  ],
  departmentIdList: [
    { required: true, message: "请选择所属部门", trigger: "change" },
  ],
};

const performRef = ref();
const performList = ref([
  {
    type: "select",
    key: "roleIdList",
    width: "260px",
    list: [],
    label: "员工角色",
    clearable: true,
    loading: false,
    multiple: true,
    remote: true,
  },
  {
    label: "数据权限",
    type: "perSelect",
    key: "pername2",
    mianHeight: "430px",
    show: true,
    loading: false,
    config: {
      first: {
        key: "firstKey",
        List: [],
        name: "商户分组",
      },
      second: {
        key: "secondKey",
        List: [],
        name: "门店分组",
      },
      thrid: {
        key: "thridKey",
        List: [],
        name: "门店经营品牌",
      },
    },
  },
]);

const performRules = {
  roleIdList: [
    { required: true, message: "请选择员工角色", trigger: "change" },
  ],
  pername2: [
    {
      required: true,
      message: "请选择数据权限",
      trigger: "change",
    },
  ],
};
const saveLoading = ref(false)
const sumbit = async () => {
  Promise.all([
    baseformRef.value?.submitForm(),
    performRef.value?.submitForm(),
  ]).then((res) => {
    if (res.map((v) => v.state).some((v) => !v)) {
      const item = res.filter((v) => !v.state)[0].data;
      const messages = Object.values(item)[0];
      return ElMessage({
        showClose: true,
        message: messages[0].message,
        type: "error",
      });
    }
    sumbitEnd(res);
  });
};

// 最后提价处理
const sumbitEnd = async (res) => {
  let obj = {};
  res
    .map((v) => v.data)
    .forEach((e) => {
      obj = { ...obj, ...e };
    });
  const submitObj = JSON.parse(JSON.stringify(obj));
  if (submitObj.userPassword == "********") {
    delete submitObj.userPassword;
  }else{
    submitObj.userPassword = md5(submitObj.userPassword);
  }
  submitObj.merchantGroupingIdList = obj.pername2.firstKey;
  submitObj.storeGroupingIdList = obj.pername2.secondKey;
  submitObj.storeManagementBrandGroupingIdList = obj.pername2.thridKey;
  delete submitObj.pername2;
  if (!submitObj.merchantGroupingIdList.length) {
    return ElMessage({
      showClose: true,
      message: "商户分组不能为空",
      type: "error",
    });
  }
  if (!submitObj.storeGroupingIdList.length) {
    return ElMessage({
      showClose: true,
      message: "门店分组不能为空",
      type: "error",
    });
  }
  if (!submitObj.storeManagementBrandGroupingIdList.length) {
    return ElMessage({
      showClose: true,
      message: "门店管理品牌分组不能为空",
      type: "error",
    });
  }
  saveLoading.value = true
  await operationSysUser({ ...submitObj, id: submitId.value });
  saveLoading.value = false
  sessionStorage.setItem('closeTagName','StaffManageEdit');
  closeBack();
};
const modalRef = ref();
const seachTableRef = ref();
const showConfirm = () => {
  // 弹框
  const performRes = performRef.value?.formModel.pername2;
  const merchantGroupIdList = performRes.firstKey || [];
  const storeGroupIdList = performRes.secondKey || [];
  const brandIdList = performRes.thridKey || [];
  if (!merchantGroupIdList.length) {
    return ElMessage({
      showClose: true,
      message: "商户分组不能为空",
      type: "error",
    });
  }
  if (!storeGroupIdList.length) {
    return ElMessage({
      showClose: true,
      message: "门店分组不能为空",
      type: "error",
    });
  }
  if (!brandIdList.length) {
    return ElMessage({
      showClose: true,
      message: "门店管理品牌分组不能为空",
      type: "error",
    });
  }
  modalRef.value.open();
};
const formInline = ref([
  {
    type: "input",
    prop: "keywords",
    placeholder: "员工姓名/登录帐号",
    label: "",
    model: "",
  },
]);
const tableLoading = ref(false);
const totalPage = ref(0);
const tableData = ref([]);
const tableConfig = ref([
  {
    prop: "code",
    label: "门店ID",
    width: "160",
  },
  {
    prop: "licenseName",
    label: "营业执照名称",
    width: "120",
  },
  {
    prop: "storeName",
    label: "门店名称",
    width: "120",
  },
  {
    prop: "enterpriseName",
    label: "所属商户",
    width: "100",
  },
  {
    prop: "busiGroupId",
    label: "商户分组",
    width: "100",
    type: "slot",
    slotName: "busiGroupId",
  },
  {
    prop: "managementWay",
    label: "经营方式",
    width: "100",
    type: "slot",
    slotName: "managementWay",
  },
  {
    prop: "brandId",
    label: "经营品牌",
    width: "120",
    type: "slot",
    slotName: "brandId",
  },
  {
    prop: "addr",
    label: "所属地区",
    width: "150",
  },
  {
    prop: "storeGroupId",
    label: "门店分组",
    width: "100",
    type: "slot",
    slotName: "storeGroupId",
  },
  {
    prop: "createTime",
    label: "创建时间",
    minWidth: "220",
  },
]);
const handlerSearch = async (formInline) => {
  performList.value[1].storeCount = 0
  const performRes = performRef.value?.formModel.pername2;
  const merchantGroupIdList = performRes.firstKey || [];
  const storeGroupIdList = performRes.secondKey || [];
  const brandIdList = performRes.thridKey || [];
  if(!merchantGroupIdList.length || !storeGroupIdList.length || !brandIdList.length){
    return
  }
  tableLoading.value = true;
  try {
    const { total, records } = await dataGroupAuthStore({
      ...formInline,
      merchantGroupIdList,
      storeGroupIdList,
      brandIdList,
    });
    totalPage.value = total;
    tableData.value = records;
    performList.value[1].storeCount = total;
    tableLoading.value = false;
  } catch (e) {
    tableLoading.value = false;
  }
};
const modalDestroy = () => {
  modalRef.value.close();
  nextTick(() => {
    seachTableRef.value.clearForm()
  });
};
const topBarRef = ref();
const closeBack = () => {
  topBarRef.value.backHandle();
};
const uuid = computed(() => {
  return route.query.uuid;
});
const submitId = ref();

onActivated(async () => {
  baseformList.value[3].loading = true;
  const depRes = await queryDepartmentListPage();
  baseformList.value[3].list = depRes.records.map((v) => ({
    label: v.departmentName,
    value: v.id,
  }));
  baseformList.value[3].loading = false;

  performList.value[0].loading = true;
  const performRes = await queryRoleList();
  performList.value[0].list = performRes.records.map((v) => ({
    label: v.roleName,
    value: v.id,
  }));
  performList.value[0].loading = false;

  performList.value[1].loading = true;
  const performRes1 = await queryDataPermissionList({
    page: { size: 99999, current: 1 },
    permissionType: 1,
  });
  performList.value[1].config.first.List = performRes1.records.map((v) => ({
    label: v.permissionName,
    value: v.id,
    storeCount: v.storeCount,
  }));
  const performRes2 = await queryDataPermissionList({
    page: { size: 99999, current: 1 },
    permissionType: 2,
  });

  performList.value[1].config.second.List = performRes2.records.map((v) => ({
    label: v.permissionName,
    value: v.id,
    storeCount: v.storeCount,
  }));
  const performRes3 = await queryDataPermissionList({
    page: { size: 99999, current: 1 },
    permissionType: 3,
  });

  performList.value[1].config.thrid.List = performRes3.records.map((v) => ({
    label: v.permissionName,
    value: v.id,
    storeCount: v.storeCount,
  }));

  performList.value[1].loading = false;

  const infoRef = await querySysUserDetail(uuid.value);
  baseformRef.value.setForm({
    departmentIdList: infoRef.departmentIdList,
    employeeName: infoRef.employeeName,
    userAccount: infoRef.userAccount,
    userRemark: infoRef.userRemark,
    userPassword: "********",
  });

  performRef.value.setForm({
    roleIdList: infoRef.roleIdList,
    firstKey: infoRef.merchantGroupingIdList,
    secondKey: infoRef.storeGroupingIdList,
    thridKey: infoRef.storeManagementBrandGroupingIdList,
  });
  submitId.value = infoRef.id;
  setStore();
});
const setStore = () => {
  handlerSearch({ page: { size: 99999, current: 1 } });
};
</script>
<template>
  <Topbar ref="topBarRef" :tabName="'编辑员工'">
    <template #operate>
      <el-button style="min-width: 68px" @click="closeBack">取消</el-button>
      <el-button type="primary" style="min-width: 68px" @click="sumbit" :loading="saveLoading"
        >保存</el-button
      >
    </template>
  </Topbar>
  <div class="pl24 pt24 pr24 content_mians">
    <FormTitle class="mb16" :titleName="'基础信息'"></FormTitle>
    <Form
      ref="baseformRef"
      :formList="baseformList"
      :formRules="baseformRules"
      labelWidth="80px"
      isInline
      :isCustomizeClass="'grid grid-template-columns-3 grid-gap-39  align-items-center'"
    ></Form>
    <FormTitle class="mb16 mt8" :titleName="'权限设置'"></FormTitle>
    <Form
      ref="performRef"
      :formList="performList"
      :formRules="performRules"
      labelWidth="80px"
      @confirm="showConfirm"
      @perChange="setStore"
    ></Form>
  </div>
  <Modal
    ref="modalRef"
    :width="'70%'"
    :top="'15vh'"
    :title="'门店数据'"
    class="staffModalStyle"
    @destroy="modalDestroy"
  >
    <template #content>
      <SeachTable
        :tableType="1"
        style="height: 600px;"
        ref="seachTableRef"
        :forms="formInline"
        :tableLoading="tableLoading"
        :tableConfig="tableConfig"
        :tableData="tableData"
        :showBtn="false"
        :totalPage="totalPage"
        :showLine="false"
        @handlerSearch="handlerSearch"
      >
        <template #managementWay="{row}">
          {{ row.managementWay == 1 ?'直营':'加盟' }}
        </template>
        <template #brandId="{ row }">
          <div v-if="row.brandId">
            <span v-for="(item, index) in row.brandId.split(',')" :key="index">
              {{ performList[1].config.thrid.List?.find(v=>v.value == item)?.label }}
            </span>
          </div>
          <div v-else>-</div>
        </template>
        <template #busiGroupId="{ row }">
          <div v-if="row.busiGroupId">
            <span v-for="(item, index) in row.busiGroupId.split(',')" :key="index">
              <!-- <TabelBrand :id="item" :type="1"></TabelBrand> -->
              {{ performList[1].config.first.List?.find(v=>v.value == item)?.label }}
            </span>
          </div>
          <div v-else>-</div>
        </template>
        <template #storeGroupId="{ row }">
          <div v-if="row.storeGroupId">
            <span v-for="(item, index) in row.storeGroupId.split(',')" :key="index">
              {{ performList[1].config.second.List?.find(v=>v.value == item)?.label }}

            </span>
          </div>
          <div v-else>-</div>
        </template>
      </SeachTable>
    </template>
    <!-- <template #footer>
      <div class="mt16">
        <el-button @click="modalDestroy">取消</el-button>
        <el-button type="primary">确定</el-button>
      </div>
    </template> -->
  </Modal>
</template>

<style lang="less" scoped>
.content_mians {
  height: calc(100% - 80px);
  overflow: auto;
}
</style>
